<template>
  <div class="main-layout">
    <div class="post-detail-card">
      <!-- 返回按钮行 -->
      <div class="post-detail-header-row">
        <button class="chat-back-btn" @click="goBack">
          <svg
            xmlns="http://www.w3.org/2000/svg"
            width="22"
            height="22"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
            stroke-linecap="round"
            stroke-linejoin="round"
          >
            <line x1="19" y1="12" x2="5" y2="12"></line>
            <polyline points="12 19 5 12 12 5"></polyline>
          </svg>
          返回
        </button>
      </div>
      <div class="post-detail-content">
        <div v-if="showToast" class="toast">{{ toastMsg }}</div>
        <template v-if="loading">
          <div class="loading">加载中...</div>
        </template>
        <template v-else-if="errorMsg">
          <div class="error-msg">{{ errorMsg }}</div>
        </template>
        <template v-else>
          <!-- 头部：头像昵称时间 -->
          <div class="post-header">
            <router-link
              :to="{
                name: 'user-profile',
                params: { id: post.userId },
                query: { nickname: post.userNickname },
              }"
              class="avatar-link"
            >
              <img class="avatar" :src="getUserAvatar(post.userPhoto, post.userId)" alt="头像" />
            </router-link>
            <router-link
              :to="{
                name: 'user-profile',
                params: { id: post.userId },
                query: { nickname: post.userNickname },
              }"
              class="nickname-link"
            >
              <div class="nickname">{{ post.userNickname }}</div>
            </router-link>
            <div class="time">{{ post.addTime }}</div>
          </div>
          <!-- 正文 -->
          <div class="post-content">{{ post.content }}</div>
          <!-- 操作区 -->
          <div class="post-actions">
            <button class="like-btn" :class="{ liked: isLiked }" @click="handleLike">
              <svg viewBox="0 0 20 20" width="20" height="20" fill="currentColor">
                <path
                  d="M10 18c-.26 0-.52-.1-.72-.29C7.1 15.66 2 11.05 2 7.5 2 4.42 4.42 2 7.5 2c1.54 0 3.04.81 3.88 2.09C12.46 2.81 13.96 2 15.5 2 18.58 2 21 4.42 21 7.5c0 3.55-5.1 8.16-7.28 10.21-.2.19-.46.29-.72.29z"
                ></path>
              </svg>
              <span>{{ likeCount }}</span>
            </button>
            <button class="comment-btn" @click="handleShowCommentInput">
              <svg viewBox="0 0 20 20" width="20" height="20" fill="currentColor">
                <path
                  d="M18 10c0 3.31-3.13 6-7 6-.98 0-1.92-.13-2.8-.36l-4.11 1.13a1 1 0 01-1.23-1.23l1.13-4.11A6.96 6.96 0 012 10c0-3.31 3.13-6 7-6s7 2.69 7 6z"
                ></path>
              </svg>
              <span>{{ commentCount }}</span>
            </button>
          </div>
          <!-- 评论输入框 -->
          <div v-if="showCommentInput" class="comment-input-box">
            <textarea v-model="commentContent" placeholder="说点什么..." rows="3" />
            <div class="input-actions">
              <button class="submit-btn" @click="handleSubmitComment">发布评论</button>
              <button class="cancel-btn" @click="handleCancelComment">取消</button>
            </div>
          </div>
          <!-- 评论区 -->
          <div class="comment-section">
            <template v-if="comments.length === 0">
              <div class="no-comment">还没有评论，快来抢沙发吧！</div>
            </template>
            <template v-else>
              <CommentItem
                v-for="c in comments"
                :key="c.id"
                :comment="c"
                :current-user-id="currentUserId"
                :show-reply-input="showReplyInput"
                :replying-to="replyingTo"
                :reply-content="replyContent"
                @show-reply-input="handleShowReplyInput"
                @cancel-reply="handleCancelReply"
                @submit-reply="handleSubmitReply"
                @delete-comment="handleDeleteComment"
              />
            </template>
            <!-- 分页按钮 -->
            <div v-if="commentPages > 1" class="comment-pagination">
              <button :disabled="commentPage === 1" @click="fetchComments(commentPage - 1)">
                上一页
              </button>
              <span>第{{ commentPage }}页 / 共{{ commentPages }}页</span>
              <button
                :disabled="commentPage === commentPages"
                @click="fetchComments(commentPage + 1)"
              >
                下一页
              </button>
            </div>
          </div>
          <!-- 删除确认弹窗 -->
          <div v-if="showDeleteConfirm" class="delete-confirm-mask">
            <div class="delete-confirm-dialog">
              <div class="confirm-title">确定要删除这条评论吗？</div>
              <div class="confirm-actions">
                <button class="submit-btn" @click="confirmDelete">确定</button>
                <button class="cancel-btn" @click="cancelDelete">取消</button>
              </div>
            </div>
          </div>
        </template>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import CommentItem from '@/components/CommentItem.vue'
import api from '@/services/api'
import { getUserAvatar } from '@/utils/avatar'

const route = useRoute()
const postId = route.params.id
const loading = ref(true)
const errorMsg = ref('')
const post = ref({})
const comments = ref([]) // 拍平后的评论数组
const rawComments = ref([]) // 原始后端返回的一级评论数组
const commentPage = ref(1)
const commentPageSize = 10
const commentTotal = ref(0)
const commentPages = ref(1)
const isLiked = ref(false)
const likeCount = ref(0)
const commentCount = ref(0)
const showCommentInput = ref(false)
const commentContent = ref('')
const replyingTo = ref(null) // 当前正在回复的评论id
const replyContent = ref('')
const showReplyInput = reactive({}) // 控制每条评论的回复框显示
const showDeleteConfirm = ref(false)
const deleteTarget = ref(null)

// 模拟当前登录用户id
const currentUserId = 101

// 简单弹窗提示
const toastMsg = ref('')
const showToast = ref(false)
function showAutoToast(msg) {
  toastMsg.value = msg
  showToast.value = true
  setTimeout(() => (showToast.value = false), 1800)
}

async function fetchPostDetail() {
  loading.value = true
  errorMsg.value = ''
  try {
    const res = await api.fetchPostDetail(postId)
    if (res.data && res.data.code === 0) {
      post.value = res.data.data
      isLiked.value = res.data.data.isLiked
      likeCount.value = res.data.data.likeCount
      commentCount.value = res.data.data.commentCount
      // 调试输出后端返回的头像路径
      console.log('[DEBUG] userPhoto from backend:', post.value.userPhoto)
    } else {
      errorMsg.value = res.data?.msg || '获取帖子详情失败'
    }
  } catch {
    errorMsg.value = '获取帖子详情失败'
  } finally {
    loading.value = false
  }
}

// 拍平评论，一级顶格，所有子评论统一缩进一层，子评论显示父昵称
function flattenComments(rawList) {
  const flat = []
  const idToNickname = {}
  // 先收集所有id和昵称
  function collectNicknames(list) {
    for (const c of list) {
      idToNickname[c.id] = c.userNickname
      if (c.children && c.children.length) {
        collectNicknames(c.children)
      }
    }
  }
  collectNicknames(rawList)

  // 递归拍平所有评论
  function walk(list, isChild = false) {
    for (const c of list) {
      flat.push({
        ...c,
        isChild,
        parentNickname: isChild ? idToNickname[c.parentId] || '' : '',
      })
      if (c.children && c.children.length) {
        console.log(`[DEBUG] 递归处理子评论，父id=${c.id}，子数=${c.children.length}`)
        walk(c.children, true)
      }
    }
  }
  walk(rawList, false)
  console.log('[DEBUG] flattenComments结果:', JSON.parse(JSON.stringify(flat)))
  return flat
}

// 分页加载评论
async function fetchComments(page = 1) {
  try {
    const res = await api.fetchComments(postId, page, commentPageSize)
    if (res.data && res.data.code === 0) {
      rawComments.value = res.data.data.comments || []
      commentTotal.value = res.data.data.total || 0
      commentPages.value = res.data.data.pages || 1
      console.log('[DEBUG] 原始后端评论数据:', JSON.parse(JSON.stringify(rawComments.value)))
      comments.value = flattenComments(rawComments.value)
      console.log('[DEBUG] 拍平后评论数组:', JSON.parse(JSON.stringify(comments.value)))
      commentPage.value = page
    } else {
      errorMsg.value = res.data?.msg || '获取评论失败'
    }
  } catch {
    errorMsg.value = '获取评论失败'
  }
}

onMounted(async () => {
  await fetchPostDetail()
  await fetchComments(1)
})

async function handleLike() {
  try {
    const res = await api.likePost(postId)
    if (res.data && res.data.code === 0) {
      isLiked.value = res.data.data.liked
      likeCount.value = res.data.data.likeCount
    } else {
      showAutoToast(res.data?.msg || '操作失败')
    }
  } catch {
    showAutoToast('点赞请求失败')
  }
}

function handleShowCommentInput() {
  showCommentInput.value = true
  commentContent.value = ''
}
function handleCancelComment() {
  showCommentInput.value = false
  commentContent.value = ''
}
async function handleSubmitComment() {
  if (!commentContent.value.trim()) return
  try {
    const res = await api.addComment({ postId, content: commentContent.value })
    if (res.data && res.data.code === 0) {
      showAutoToast('评论成功')
      await fetchComments(commentPage.value)
      commentCount.value++
      showCommentInput.value = false
      commentContent.value = ''
    } else {
      showAutoToast(res.data?.msg || '评论失败')
    }
  } catch {
    showAutoToast('评论请求失败')
  }
}
function handleShowReplyInput(commentId) {
  showReplyInput[commentId] = true
  replyingTo.value = commentId
  replyContent.value = ''
}
function handleCancelReply(commentId) {
  showReplyInput[commentId] = false
  replyContent.value = ''
  replyingTo.value = null
}
async function handleSubmitReply({ parent, content }) {
  if (!content.trim()) return
  try {
    const res = await api.addComment({ postId, content, parentId: parent.id })
    if (res.data && res.data.code === 0) {
      showAutoToast('回复成功')
      await fetchComments(commentPage.value)
      commentCount.value++
      showReplyInput[parent.id] = false
      replyContent.value = ''
      replyingTo.value = null
    } else {
      showAutoToast(res.data?.msg || '回复失败')
    }
  } catch {
    showAutoToast('回复请求失败')
  }
}
function handleDeleteComment(comment, parent) {
  showDeleteConfirm.value = true
  deleteTarget.value = { comment, parent }
}
function confirmDelete() {
  const { comment, parent } = deleteTarget.value
  if (parent) {
    parent.children = parent.children.filter((c) => c.id !== comment.id)
  } else {
    comments.value = comments.value.filter((c) => c.id !== comment.id)
  }
  commentCount.value--
  showDeleteConfirm.value = false
  deleteTarget.value = null
}
function cancelDelete() {
  showDeleteConfirm.value = false
  deleteTarget.value = null
}
function goBack() {
  window.history.back()
}
</script>

<style scoped>
.main-layout {
  display: flex;
  flex-direction: column;
  align-items: center;
  min-height: 100vh;
  background: var(--color-bg);
}
.post-detail-card {
  width: 100%;
  max-width: 1200px;
  margin: 2.5rem auto 0 auto;
  background: var(--color-input-bg);
  border-radius: 0.7rem;
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.1);
  padding: 0;
  box-sizing: border-box;
  min-height: 300px;
}
.post-detail-header-row {
  display: flex;
  align-items: center;
  height: 3.5rem;
  padding: 0 1.5rem;
  background: var(--color-input-bg);
  border-top-left-radius: 0.7rem;
  border-top-right-radius: 0.7rem;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.04);
  z-index: 2;
  margin-top: 1.2rem;
}
.post-detail-content {
  padding: 2.5rem 1.5rem 2.5rem 1.5rem;
}
@media (max-width: 700px) {
  .post-detail-card {
    max-width: 100%;
    padding: 0;
  }
  .post-detail-header-row {
    padding: 0 0.5rem;
    height: 3rem;
    margin-top: 0.7rem;
  }
  .post-detail-content {
    padding: 1.5rem 0.5rem 2rem 0.5rem;
  }
}
.chat-back-btn {
  display: flex;
  align-items: center;
  gap: 0.3rem;
  background: var(--color-surface, var(--color-input-bg));
  color: var(--color-text);
  border: 1px solid var(--color-border);
  border-radius: 0.4rem;
  padding: 0.4rem 0.9rem;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition:
    background 0.2s,
    color 0.2s;
}
.chat-back-btn:hover {
  background: var(--color-surface-hover, #f5f7fa);
  color: var(--color-primary);
}
.post-header {
  display: flex;
  align-items: center;
  gap: 1.5rem;
  margin-bottom: 2rem;
}
.avatar-link .avatar {
  width: 4rem;
  height: 4rem;
  border-radius: 50%;
  object-fit: cover;
  border: 2.5px solid var(--color-primary);
  background: var(--color-surface, var(--color-input-bg));
  box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.08);
  transition:
    box-shadow 0.18s,
    border-color 0.18s;
}
.avatar-link .avatar:hover {
  box-shadow: 0 0 28px 10px var(--color-primary-glow, #5eb3ff);
  border-color: var(--color-primary-hover, #409eff);
}
.nickname-link {
  margin-left: 1.1rem;
  margin-right: 1.1rem;
  display: flex;
  align-items: center;
  text-decoration: none;
}
.nickname-link .nickname {
  font-weight: 600;
  color: var(--color-primary);
  font-size: 1.15rem;
  cursor: pointer;
  transition: text-shadow 0.18s;
}
.nickname-link .nickname:hover {
  text-shadow: 0 0 6px var(--color-primary-alpha, rgba(64, 158, 255, 0.18));
}
.time {
  margin-left: auto;
  color: var(--color-text-secondary);
  font-size: 1rem;
}
.post-content {
  font-size: 1.15rem;
  color: var(--color-text);
  margin-bottom: 1.5rem;
  word-break: break-all;
}
.post-actions {
  display: flex;
  align-items: center;
  gap: 2.2rem;
  margin-bottom: 1.2rem;
}
.like-btn,
.comment-btn {
  display: flex;
  align-items: center;
  gap: 0.4rem;
  background: none;
  border: none;
  color: var(--color-text-secondary);
  font-size: 1.1rem;
  cursor: pointer;
  padding: 0.3rem 0.7rem;
  border-radius: 0.3rem;
  transition:
    background 0.2s,
    color 0.2s;
}
.like-btn.liked {
  color: #e74c3c;
  font-weight: 700;
}
.like-btn:hover,
.comment-btn:hover {
  background: var(--color-primary-hover);
  color: var(--color-button-text);
}
.comment-input-box,
.reply-input-box {
  margin-bottom: 1.2rem;
  background: var(--color-surface, var(--color-input-bg));
  border-radius: 0.4rem;
  box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.08);
  padding: 1rem 1rem 0.7rem 1rem;
  display: flex;
  flex-direction: column;
  gap: 0.7rem;
}
.comment-input-box textarea,
.reply-input-box textarea {
  width: 100%;
  min-height: 3.2rem;
  font-size: 1rem;
  border: 1px solid var(--color-border-input);
  border-radius: 0.25rem;
  padding: 0.7rem 1rem;
  background: var(--color-surface, var(--color-input-bg));
  color: var(--color-text);
  resize: none;
  transition: border-color 0.2s;
}
.input-actions {
  display: flex;
  gap: 1.2rem;
  justify-content: flex-end;
}
.submit-btn {
  background: var(--color-primary);
  color: var(--color-button-text);
  border: none;
  border-radius: 0.25rem;
  padding: 0.6rem 1.2rem;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.1);
  transition: background 0.2s;
}
.submit-btn:hover:not(:disabled) {
  background: var(--color-primary-hover);
}
.cancel-btn {
  background: none;
  border: none;
  color: var(--color-text-secondary);
  font-size: 1rem;
  cursor: pointer;
  text-decoration: underline;
  padding: 0.6rem 1.2rem;
  border-radius: 0.25rem;
  transition: color 0.2s;
}
.cancel-btn:hover {
  color: var(--color-primary);
}
.comment-section {
  margin-top: 1.5rem;
}
.no-comment {
  color: var(--color-text-secondary);
  text-align: center;
  font-size: 1.1rem;
  margin: 2rem 0;
}
.comment-item {
  margin-bottom: 1.5rem;
  padding-left: 0.2rem;
}
.comment-header {
  display: flex;
  align-items: center;
  gap: 1rem;
}
.comment-header .avatar {
  width: 2.2rem;
  height: 2.2rem;
  border-radius: 50%;
  object-fit: cover;
  border: 1.5px solid var(--color-primary);
}
.comment-header .nickname {
  font-weight: 500;
  color: var(--color-primary);
  font-size: 1.05rem;
}
.comment-header .time {
  margin-left: auto;
  color: var(--color-text-secondary);
  font-size: 0.95rem;
}
.comment-content {
  font-size: 1.05rem;
  color: var(--color-text);
  margin: 0.5rem 0 0.2rem 0;
  word-break: break-all;
}
.comment-actions {
  display: flex;
  gap: 1.2rem;
  margin-bottom: 0.2rem;
  margin-top: 0.1rem;
}
.reply-btn,
.delete-btn {
  background: none;
  border: none;
  color: var(--color-text-secondary);
  font-size: 1rem;
  cursor: pointer;
  text-decoration: underline;
  padding: 0;
  border-radius: 0.25rem;
  transition: color 0.2s;
}
.reply-btn:hover,
.delete-btn:hover {
  color: var(--color-primary);
}
.comment-children {
  margin-left: 2.2rem;
  border-left: 2px solid var(--color-border);
  padding-left: 1.2rem;
  margin-top: 0.7rem;
}
.delete-confirm-mask {
  position: fixed;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.18);
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
}
.delete-confirm-dialog {
  background: var(--color-input-bg);
  border-radius: 0.5rem;
  box-shadow: 0 4px 24px 0 rgba(0, 0, 0, 0.18);
  padding: 2rem 2.5rem 1.5rem 2.5rem;
  min-width: 260px;
  text-align: center;
}
.confirm-title {
  font-size: 1.15rem;
  color: var(--color-text);
  margin-bottom: 1.2rem;
}
.confirm-actions {
  display: flex;
  gap: 2rem;
  justify-content: center;
  margin-top: 1.2rem;
}
.comment-pagination {
  margin-top: 1.5rem;
  text-align: center;
}
.comment-pagination button {
  background: none;
  border: none;
  color: var(--color-text-secondary);
  font-size: 1rem;
  cursor: pointer;
  padding: 0.5rem 1rem;
  margin: 0 0.5rem;
  transition: color 0.2s;
}
.comment-pagination button:hover {
  color: var(--color-primary);
}
.toast {
  position: fixed;
  top: 2.5rem;
  left: 50%;
  transform: translateX(-50%);
  min-width: 120px;
  max-width: 80vw;
  background: #222c;
  color: #fff;
  padding: 0.8rem 1.6rem;
  border-radius: 0.7rem;
  font-size: 1.1rem;
  text-align: center;
  z-index: 9999;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.18);
  pointer-events: none;
  opacity: 0.97;
  transition: opacity 0.2s;
}
</style>
